package com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.feedback

import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.helasasa.maxfunds.lineofcredit.cashloan.R
import com.helasasa.maxfunds.lineofcredit.cashloan.databinding.ActivityGhanaFeedbackBinding
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.hitPoint
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.login.afterTextChanged
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.subview.HotlineGhanaDialog
import com.vmadalin.easypermissions.EasyPermissions
import com.vmadalin.easypermissions.dialogs.DEFAULT_SETTINGS_REQ_CODE
import com.vmadalin.easypermissions.dialogs.SettingsDialog

class FeedbackGhanaActivity : AppCompatActivity(), EasyPermissions.PermissionCallbacks,
    EasyPermissions.RationaleCallbacks {

    private lateinit var feedbackViewModel: FeedbackGhanaViewModel
    private lateinit var binding: ActivityGhanaFeedbackBinding
    private lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 数据模型
        feedbackViewModel = ViewModelProvider(this)[FeedbackGhanaViewModel::class.java]

        // 关联布局
        binding = ActivityGhanaFeedbackBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 用到的控件
        val hotline = binding.navbarRight
        val back = binding.navbarLeft
        val save = binding.save
        val loading = binding.loading

        // 页面loading状态接口监听
        feedbackViewModel.loadingResult.observe(this@FeedbackGhanaActivity, Observer {
            val loadingResult = it ?: return@Observer

            if (loadingResult) {
                loading.visibility = View.VISIBLE
            } else {
                loading.visibility = View.GONE
            }
        })

        // 页面UI状态接口监听
        feedbackViewModel.pageDetailResult.observe(this@FeedbackGhanaActivity, Observer {
            val pageDetailResult = it ?: return@Observer

            loading.visibility = View.GONE
            selectType(
                pageDetailResult.type,
                pageDetailResult.input,
                pageDetailResult.picBitmaps
            )
        })

        // 流程接口监听
        feedbackViewModel.saveFeedbackResult.observe(this@FeedbackGhanaActivity, Observer {
            val saveFeedbackResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (saveFeedbackResult.error != null) {
                showMessage(saveFeedbackResult.error)
            }

            if (saveFeedbackResult.success) {
                showMessage("Submit success!")
                // 重置
                feedbackViewModel.reset()
            }
        })

        // 跳转相册监听
        pickMedia =
            registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
                if (uri != null) {
                    feedbackViewModel.handlePickImageResult(
                        this@FeedbackGhanaActivity,
                        uri
                    )
                } else {
                    Log.d("PhotoPicker", "No media selected")
                }
            }

        // 输入监听
        binding.input.afterTextChanged {
            feedbackViewModel.inputChanged(binding.input.text.toString())
        }

        // 点击保存
        save.setOnClickListener {
            loading.visibility = View.VISIBLE
            feedbackViewModel.saveFeedbackInfo()
            hitPoint("FEEDBACK_COMMIT")
        }

        // 点击客服
        hotline.setOnClickListener {
            // 客服弹框
            HotlineGhanaDialog().showNow(supportFragmentManager, "hotline")
            hitPoint("SHOW_HOTLINE")
        }

        // 点击返回
        back.setOnClickListener {
            finish()
        }

        // 点击suggess
        binding.product.setOnClickListener {
            feedbackViewModel.typeChanged(binding.product.tag.toString())
            hitPoint("FEEDBACK_TYPE_CLICK", binding.product.tag.toString())
        }

        // 点击payment
        binding.payment.setOnClickListener {
            feedbackViewModel.typeChanged(binding.payment.tag.toString())
            hitPoint("FEEDBACK_TYPE_CLICK", binding.payment.tag.toString())
        }

        // 点击bugs
        binding.bugs.setOnClickListener {
            feedbackViewModel.typeChanged(binding.bugs.tag.toString())
            hitPoint("FEEDBACK_TYPE_CLICK", binding.bugs.tag.toString())
        }

        // 点击other
        binding.other.setOnClickListener {
            feedbackViewModel.typeChanged(binding.other.tag.toString())
            hitPoint("FEEDBACK_TYPE_CLICK", binding.other.tag.toString())
        }

        // 点击添加图片
        binding.add.setOnClickListener {
            if (askCameraPermission()) return@setOnClickListener

            val curPics = feedbackViewModel.pageDetailResult.value?.picBitmaps?.size ?: 0
            if (curPics >= 2) {
                showMessage("Upload up to two images.")
                return@setOnClickListener
            }

            // ablum
            pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
        }

        // 点击删除1
        binding.delete1.setOnClickListener {
            feedbackViewModel.deletePic(0)
        }

        // 点击删除2
        binding.delete2.setOnClickListener {
            feedbackViewModel.deletePic(1)
        }
    }

    /**
     * 更新类型选择UI
     */
    @SuppressLint("SetTextI18n")
    private fun selectType(
        type: String? = null,
        input: String? = null,
        picBitmaps: List<Bitmap>? = null
    ) {
        type?.let {
            if (it.contains("SUGGEST", true)) {
                binding.product.setBackgroundResource(R.drawable.bg_blue_cor_17dp)
                binding.product.setTextColor(Color.parseColor("#FFFFFF"))

                binding.payment.setBackgroundResource(R.drawable.bg_feedback_uncheck)
                binding.payment.setTextColor(Color.parseColor("#828282"))

                binding.bugs.setBackgroundResource(R.drawable.bg_feedback_uncheck)
                binding.bugs.setTextColor(Color.parseColor("#828282"))

                binding.other.setBackgroundResource(R.drawable.bg_feedback_uncheck)
                binding.other.setTextColor(Color.parseColor("#828282"))

            } else if (it.contains("PAYMENT", true)) {
                binding.product.setBackgroundResource(R.drawable.bg_feedback_uncheck)
                binding.product.setTextColor(Color.parseColor("#828282"))

                binding.payment.setBackgroundResource(R.drawable.bg_blue_cor_17dp)
                binding.payment.setTextColor(Color.parseColor("#FFFFFF"))

                binding.bugs.setBackgroundResource(R.drawable.bg_feedback_uncheck)
                binding.bugs.setTextColor(Color.parseColor("#828282"))

                binding.other.setBackgroundResource(R.drawable.bg_feedback_uncheck)
                binding.other.setTextColor(Color.parseColor("#828282"))

            } else if (it.contains("BUG", true)) {
                binding.product.setBackgroundResource(R.drawable.bg_feedback_uncheck)
                binding.product.setTextColor(Color.parseColor("#828282"))

                binding.payment.setBackgroundResource(R.drawable.bg_feedback_uncheck)
                binding.payment.setTextColor(Color.parseColor("#828282"))

                binding.bugs.setBackgroundResource(R.drawable.bg_blue_cor_17dp)
                binding.bugs.setTextColor(Color.parseColor("#FFFFFF"))

                binding.other.setBackgroundResource(R.drawable.bg_feedback_uncheck)

                binding.other.setTextColor(Color.parseColor("#828282"))

            } else if (it.contains("OTHER", true)) {
                binding.product.setBackgroundResource(R.drawable.bg_feedback_uncheck)
                binding.product.setTextColor(Color.parseColor("#828282"))

                binding.payment.setBackgroundResource(R.drawable.bg_feedback_uncheck)
                binding.payment.setTextColor(Color.parseColor("#828282"))

                binding.bugs.setBackgroundResource(R.drawable.bg_feedback_uncheck)
                binding.bugs.setTextColor(Color.parseColor("#828282"))

                binding.other.setBackgroundResource(R.drawable.bg_blue_cor_17dp)
                binding.other.setTextColor(Color.parseColor("#FFFFFF"))
            }
        }

        if (input == null) {
            binding.limit.text = "0/100"
            binding.input.text = null
        } else {
            binding.limit.text = "${input.length}/100"
        }

        picBitmaps?.let {
            val size: Int = it.size
            when (size) {
                0 -> {
                    binding.pic1Bg.visibility = View.GONE
                    binding.pic1.setImageBitmap(null)

                    binding.pic2Bg.visibility = View.GONE
                    binding.pic2.setImageBitmap(null)
                }

                1 -> {
                    val bitmap = it.first()
                    binding.pic1Bg.visibility = View.VISIBLE
                    binding.pic1.setImageBitmap(bitmap)

                    binding.pic2Bg.visibility = View.GONE
                    binding.pic2.setImageBitmap(null)
                }

                else -> {
                    val bitmap1 = it[0]
                    binding.pic1Bg.visibility = View.VISIBLE
                    binding.pic1.setImageBitmap(bitmap1)

                    val bitmap2 = it[1]
                    binding.pic2Bg.visibility = View.VISIBLE
                    binding.pic2.setImageBitmap(bitmap2)
                }
            }
        }
    }

    /**
     * 请求相机权限
     */
    private fun askCameraPermission(): Boolean {
        val list = mutableListOf(android.Manifest.permission.CAMERA)
        if (checkPermissionsGranted(list)) {
            return false
        }
        // 未同意权限
        EasyPermissions.requestPermissions(
            this,
            "App will request Camera Permission",
            100,
            *(list.toTypedArray())
        )
        return true
    }

    /**
     * 检查权限是否同意
     */
    private fun checkPermissionsGranted(permissionList: List<String>): Boolean {
        val isNotAllGranted = permissionList.any {
            PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, it)
        }
        return !isNotAllGranted
    }

    // ------> EasyPermissions <------
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onRationaleAccepted(requestCode: Int) {
        askCameraPermission()
    }

    override fun onRationaleDenied(requestCode: Int) {
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            SettingsDialog.Builder(this).build().show()
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == DEFAULT_SETTINGS_REQ_CODE) {
            askCameraPermission()
        }
    }

    override fun onResume() {
        super.onResume()
        hitPoint(type = this::class.java.simpleName, isPageStart = true)
    }

    override fun onPause() {
        super.onPause()
        hitPoint(type = this::class.java.simpleName, isPageEnd = true)
    }

    fun showMessage(message: String) {
        Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
    }
}

